<template>
  <van-list
      v-model:loading="loading"
      :finished="finished"
      class="manual-relation-list"
      finished-text="没有更多了"
      @load="onLoad">
    <ManualRelationFormCard
        v-for="(item, index) in dataSource"
        :rowIndex="index"
        :fields="fields"
        :idColumnName="idColumnName"
        :formDefinition="formDefinition"
        :key="item[idColumnName]"
        :rowId="item[idColumnName]"
        :selectedRows="innerSelectedRows"
        :selectedRowsKeys="selectedRowsKeys"
        :selectionType="selectionType"
        :manualConfig="manualConfig"
        :item="item"/>
  </van-list>
</template>
<script setup>
import {computed, ref, shallowRef} from 'vue';
import ManualRelationFormCard from '@comp/FormEngine/field/relation/RelationFormList/ManualRelationFormCard.vue';
import {createProps} from '@/utils';
import {showToast} from 'vant';

defineOptions({name: 'ManualRelationList'});

const props = defineProps({
  dataSource: createProps(Array, () => []),
  selectedRows: createProps(Array, () => undefined),
  subForm: createProps(Object),
  formDefinition: createProps(Object, () => undefined),
  manualConfig: createProps(Object, () => undefined),
  context: createProps(Object, () => undefined),
  selectionType: createProps(String, 'radio'),
});
const emits = defineEmits(['update:selectedRows']);
const loading = shallowRef(false);
const finished = ref(false);

const idColumnName = computed(() => {
  return `${props?.formDefinition?.id}&formId`
})
const selectedRowsKeys = computed(() => {
  return (props?.selectedRows || []).map(item => item[idColumnName.value]);
})
const innerSelectedRows = computed({
  get() {
    let temp = props.selectedRows;
    if (!temp) {
      emits('update:selectedRows', temp = []);
    }
    return temp;
  },
  set(v) {
    emits('update:selectedRows', v);
  },
})
const onLoad = () => {
  loading.value = false;
  showToast('onLoad');

  // 异步更新数据
  // setTimeout 仅做示例，真实场景中一般为 ajax 请求
  // setTimeout(() => {
  //   for (let i = 0; i < 10; i++) {
  //     list.value.push(list.value.length + 1);
  //   }
  //
  //   // 加载状态结束
  //   loading.value = false;
  //
  //   // 数据全部加载完成
  //   if (list.value.length >= 40) {
  //     finished.value = true;
  //   }
  // }, 1000);
};
const fields = computed(() => {
  return props.manualConfig?.manual?.fieldColumns || []
})
</script>
<style scoped lang="less">
.manual-relation-list {
  background: #f0f4f7;
  padding: 1px 0 1px 0;
  min-height: 100%;
}
</style>